﻿using System;
using System.ComponentModel;
using System.Drawing;
using System.Drawing.Design;
using System.Windows.Forms;


namespace Marmat.Forms
{
    [ToolboxItem(true)]
    [ToolboxBitmap(typeof(NumericUpDown))]
    public partial class NumericBox : TextBox
    {
        public NumericBox()
        {

            // 此调用是设计器所必需的。
            this.InitializeComponent();

            // 在 InitializeComponent() 调用之后添加任何初始化。
            ((DevExpress.XtraEditors.TextEdit)this.BaseEdit).Properties.Mask.MaskType = DevExpress.XtraEditors.Mask.MaskType.Numeric;
            ((DevExpress.XtraEditors.TextEdit)this.BaseEdit).Properties.DisplayFormat.FormatType = DevExpress.Utils.FormatType.Numeric;
            this.EditMask = "n";
            ((DevExpress.XtraEditors.TextEdit)this.BaseEdit).Properties.Mask.UseMaskAsDisplayFormat = true;
        }

        /// <summary>
        /// 返回或者设置编辑框的值。
        /// </summary>        
        public new decimal? Value
        {
            get
            {
                object value;
                if (this is EditControl editControl)
                    value = editControl.Value;
                else
                    value = base.Value;
                if (value is null || value == DBNull.Value)
                    return null;
                return Convert.ToDecimal(value);
            }
            set
            {
                if (this is EditControl editControl)
                    editControl.Value = value;
                else
                    base.Value = value.ToString();
            }
        }

        [DefaultValue("n")]
        public string EditMask
        {
            get
            {
                return ((DevExpress.XtraEditors.TextEdit)this.BaseEdit).Properties.Mask.EditMask;
            }

            set
            {
                ((DevExpress.XtraEditors.TextEdit)this.BaseEdit).Properties.Mask.EditMask = value;
                ((DevExpress.XtraEditors.TextEdit)this.BaseEdit).Properties.DisplayFormat.FormatString = value;
            }
        }

        protected internal void ResetValue()
        {
            this.BaseEdit.EditValue = null;
        }

        protected internal bool ShouldSerializeValue()
        {
            return this.BaseEdit.EditValue != null;
        }
    }
}